import React, { useEffect } from "react";
import { useEditorContext } from "../../store/editor-provider";
import _ from "lodash";
import { Collapse, Form, FormProps, Input, Radio } from "antd";
import {
  ColorSeriesSelect,
  FontSizeSelect,
  getSeriesCOlor
} from "../../components/attrubute-pannel/common-settings";
import CollapsePanel from "antd/es/collapse/CollapsePanel";
import ColorSelect from "../../components/color-select";
import { useForm } from "antd/es/form/Form";
import { WidgetInfo } from "../../types";
import { baseFormLayoutConfig } from "../../components/attrubute-pannel/global-settings-pannel";
import { RegistrerWidgetProps } from "../../components/card-content";
import Chart from "../../components/chart";

interface Props extends RegistrerWidgetProps {}

const defaultConfig = {
  title: "报表标题",
  card: "跟随全局",
  chartColor: "跟随全局"
};

function BarChart(props: Props) {
  const { data } = props;
  const { editor } = useEditorContext();

  const actualComponentConfig = _.merge(
    _.cloneDeep(defaultConfig),
    props.config
  );

  const getRenderConfig = () => {
    let finalConfig = _.merge(
      _.cloneDeep(editor.golbalSettings),
      actualComponentConfig
    );
    if (actualComponentConfig.card === "跟随全局") {
      finalConfig.cardStyle = editor.golbalSettings.cardStyle;
    }
    if (actualComponentConfig.chartColor === "跟随全局") {
      finalConfig.colorSeries = editor.golbalSettings.colorSeries;
    }
    return finalConfig;
  };

  let renderConfig = getRenderConfig();

  const getOption = (data: any, config: any): echarts.EChartsOption => {
    const color = getSeriesCOlor(config.colorSeries);
    let option: echarts.EChartsOption = {
      color,
      legend: {},
      grid: { left: 10, right: 10, top: 20, bottom: 10, containLabel: true },
      tooltip: {},
      xAxis: data.xAxis,
      yAxis: {},
      series: data.series.map((s: any) => ({
        ...s,
        type: "bar"
      }))
    };
    return option;
  };

  return (
    <Chart
      theme={editor.golbalSettings.theme}
      option={getOption(data, renderConfig)}
    />
  );
}

const StyleConfig = ({ info }: { info: WidgetInfo }) => {
  const [form] = useForm();
  const { editor, dispatch } = useEditorContext();

  useEffect(() => {
    form.setFieldsValue(info.config);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [info.config]);

  let actualConfig = _.merge(_.cloneDeep(info), defaultConfig);

  const handleComponentConfigChange: FormProps["onValuesChange"] = (
    changedValue,
    allValues
  ) => {
    let finalConfig = allValues;

    if (Object.hasOwn(changedValue, "card")) {
      if (changedValue["card"] === "自定义") {
        finalConfig = {
          ...allValues,
          cardStyle: editor.golbalSettings.cardStyle
        };
      }
    }
    if (Object.hasOwn(changedValue, "chartColor")) {
      if (changedValue["chartColor"] === "自定义") {
        finalConfig = {
          ...allValues,
          colorSeries: editor.golbalSettings.colorSeries
        };
      }
    }

    dispatch({
      type: "UPDATE_CS",
      payload: { id: info.id, config: finalConfig }
    });
  };

  return (
    <div>
      <Form
        form={form}
        {...baseFormLayoutConfig}
        initialValues={actualConfig}
        onValuesChange={handleComponentConfigChange}
      >
        <Collapse defaultActiveKey={["card", "chart"]}>
          <CollapsePanel header={"卡片配置"} key={"card"}>
            <Form.Item name={["title"]} label={"标题大小"}>
              <Input placeholder={"请输入卡片标题"} />
            </Form.Item>
            <Form.Item name={["card"]} label={"卡片样式"}>
              <Radio.Group
                options={[
                  { label: "跟随全局", value: "跟随全局" },
                  { label: "自定义", value: "自定义" }
                ]}
              />
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(pre, cur) => pre.card !== cur.card}
            >
              {({ getFieldValue }) => {
                return getFieldValue("card") === "自定义" ? (
                  <>
                    <Form.Item
                      name={["cardStyle", "bgColor"]}
                      label={"卡片背景"}
                    >
                      <ColorSelect />
                    </Form.Item>
                    <Form.Item label={"标题样式"}>
                      <Form.Item name={["cardStyle", "titleSize"]} noStyle>
                        <FontSizeSelect />
                      </Form.Item>
                      <Form.Item name={["cardStyle", "titleColor"]} noStyle>
                        <ColorSelect />
                      </Form.Item>
                      <Form.Item name={["cardStyle", "titleBgColor"]} noStyle>
                        <ColorSelect />
                      </Form.Item>
                    </Form.Item>
                  </>
                ) : null;
              }}
            </Form.Item>
          </CollapsePanel>
          <CollapsePanel header={"chart配置"} key={"chart"}>
            <Form.Item label={"图表颜色"} name={"chartColor"}>
              <Radio.Group
                options={[
                  { label: "跟随全局", value: "跟随全局" },
                  { label: "自定义", value: "自定义" }
                ]}
              />
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(pre, cur) => pre.chartColor !== cur.chartColor}
            >
              {({ getFieldValue }) => {
                return getFieldValue("chartColor") === "自定义" ? (
                  <Form.Item
                    label={"色系"}
                    name={"colorSeries"}
                    shouldUpdate={(pre) => {
                      return false;
                    }}
                  >
                    <ColorSeriesSelect allowClear />
                  </Form.Item>
                ) : null;
              }}
            </Form.Item>
          </CollapsePanel>
        </Collapse>
      </Form>
    </div>
  );
};

BarChart.StyleConfig = StyleConfig;

export default BarChart;
